package com.saturday.utils;

import com.saturday.common.exception.BusinessException;

import javax.validation.*;
import java.util.Set;

public class ValidationUtils {

    private static class ValidatorInstance {
        private static Validator validator  = Validation.byDefaultProvider().configure().buildValidatorFactory().getValidator();
    }

    private static Validator getInstance() {
        return ValidatorInstance.validator;
    }


    /**
     * 返回全部校验错误信息
     * @param t
     * @param <T>
     * @return
     */
    public static <T> String  validateAll(T t) {
        Set<ConstraintViolation<T>> constraintViolations = getInstance().validate(t);
        StringBuilder errMsg = new StringBuilder();
        for (ConstraintViolation<T> violation : constraintViolations) {
            errMsg.append(violation.getMessage())
                    .append(",");
        }
        return errMsg.toString();
    }

    /**
     * 抛出第一个校验错误信息
     * @param t
     * @param <T>
     * throw BusinessException
     */
    public static <T> void  validate(T t) {
        Set<ConstraintViolation<T>> constraintViolations = getInstance().validate(t);
        if (null != constraintViolations && constraintViolations.size() > 0) {
            throw new BusinessException(constraintViolations.iterator().next().getMessage());
        }
    }
}
